package practise.mulitThreads;

import com.sun.jndi.url.corbaname.corbanameURLContextFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by richard on 4/28/14.
 */
public class CompareLockAndSynchronized {
    class SyncThread implements Runnable{

        @Override
        public void run() {
            callMethod();
        }

        synchronized void callMethod(){

        }
    }
    static Lock lock = new ReentrantLock();
    class LockClass implements Runnable{

        @Override
        public void run() {
            callMehot();
        }
        void callMehot(){
          try{
              lock.lock();
          }
          finally {
              lock.unlock();
          }
        }
    }

    public static void main(String[] args){
        CompareLockAndSynchronized compareLockAndSynchronized = new CompareLockAndSynchronized();
        List<Thread> lockClasses = new ArrayList<Thread>();
        for(int i =0 ; i < 10000; i++){
            LockClass lockClass = compareLockAndSynchronized.new LockClass();
            Thread thread = new Thread(lockClass);
            lockClasses.add(thread);
        }
        long now  = System.currentTimeMillis();
        for(Thread t : lockClasses){
            t.start();
        }

        for(Thread t : lockClasses){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Lock using :" + (System.currentTimeMillis() - now));


        List<Thread> syncClasses = new ArrayList<Thread>();
        for(int i =0 ; i < 10000; i++){
            SyncThread syncClass = compareLockAndSynchronized.new SyncThread();
            Thread thread = new Thread(syncClass);
            syncClasses.add(thread);
        }
        now  = System.currentTimeMillis();
        for(Thread t : syncClasses){
            t.start();
        }

        for(Thread t : syncClasses){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Sync using :" + (System.currentTimeMillis() - now));

    }
}
